package com.yungu.swift.system.marketing.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.yungu.swift.base.ResponseData;
import com.yungu.swift.base.mapper.IMapper;
import com.yungu.swift.base.model.admin.AdminStatusParam;
import com.yungu.swift.base.service.impl.BaseServiceImpl;
import com.yungu.swift.system.marketing.dao.MarketingActivityMapper;
import com.yungu.swift.system.marketing.model.dto.MarketingActivityDto;
import com.yungu.swift.system.marketing.model.param.AdminActivityParam;
import com.yungu.swift.system.marketing.model.param.AdminActivitySaveParam;
import com.yungu.swift.system.marketing.model.param.AdminActivitySortParam;
import com.yungu.swift.system.marketing.model.vo.AdminActivityVo;
import com.yungu.swift.system.marketing.service.MarketingActivityService;
import com.yungu.swift.utils.DateUtils;
import com.yungu.swift.utils.MapUtils;
import com.yungu.swift.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.yungu.swift.system.marketing.model.enums.MarketingErrorEnum.ACTIVITY_COUNT_LIMIT;


/**
 * <p>
 * 弹窗活动业务逻辑接口实现类
 *
 * @author xiuyin.cui - Generate
 * @version 1.1.0-SNAPSHOT
 * @since 2019-04-25 13:50
 */
@Slf4j
@Service
public class MarketingActivityServiceImpl extends BaseServiceImpl<MarketingActivityDto> implements MarketingActivityService {

    @Autowired
    private MarketingActivityMapper marketingActivityMapper;

    @Override
    protected IMapper<MarketingActivityDto> getMapper() {
        return marketingActivityMapper;
    }

    @Override
    public ResponseData<AdminActivityVo> list(AdminActivityParam activityParam) {
        AdminActivityVo adminActivityVo = new AdminActivityVo();
        // 活动列表
        adminActivityVo.setMarketingActivityDtos(marketingActivityMapper.list(MapUtils.convertObjToMap(activityParam)));
        adminActivityVo.setAdd(maxActivity(activityParam.getShowType(), activityParam.getBusinessType()));
        return ResponseData.buildSuccessResponse(adminActivityVo);
    }

    /**
     * 是否超过最大活动数量 true 没超过 false 超过
     *
     * @param showType
     * @param businessType
     * @return
     */
    private boolean maxActivity(Integer showType, Integer businessType) {
        Map<String, Object> build = MapUtils.build(8);
        build.put("showType", showType);
        build.put("businessType", businessType);
        build.put("status", 1);
        // 是否允许新增
        int count = marketingActivityMapper.activeCount(build);
        // 3 左侧栏底部、4 评价标签下部、5 启动页 只允许新建一条
        int activityMaxCount = (showType == 3 || showType == 4 || showType == 5) ? 1 : 5;
        return count < activityMaxCount;
    }

    @Override
    public ResponseData<Boolean> saveOrUpdate(AdminActivitySaveParam activitySaveParam) {
        // 查询活动数量，判断是否允许新建
        if (StringUtils.isEmpty(activitySaveParam.getUuid()) && !maxActivity(activitySaveParam.getShowType(),
                activitySaveParam.getBusinessType())) {
            return ResponseData.buildErrorResponse(ACTIVITY_COUNT_LIMIT.getCode(), ACTIVITY_COUNT_LIMIT.getMsg());
        }
        MarketingActivityDto marketingActivityDto = new MarketingActivityDto();
        BeanUtils.copyProperties(activitySaveParam, marketingActivityDto);
        if (StringUtils.isEmpty(marketingActivityDto.getCityUuid())) {
            marketingActivityDto.setCityUuid("ALL");
            marketingActivityDto.setCityName("全国");
        }
        //判断预约开启的广告是否设置的为启用状态 并且开始之前比当前时间加上一分钟（防止操作过快 所以这边加上超过一分钟的限制）要晚
        if (null != activitySaveParam.getPutInDateOn() && activitySaveParam.getPutInDateOn().after(DateUtils.addSeconds(
                new Date(), 1))) {
            //设置为未启用
            marketingActivityDto.setStatus(0);
        }
        if (StringUtils.isEmpty(marketingActivityDto.getUuid())) {
            marketingActivityDto.setUuid(StringUtils.buildUUID());
            marketingActivityDto.setSort(1);
            marketingActivityDto.setCreateOn(new Date());
            marketingActivityDto.setCreateBy(activitySaveParam.getUserUuid());
            marketingActivityMapper.add(marketingActivityDto);
        } else {
            marketingActivityDto.setUpdateOn(new Date());
            marketingActivityDto.setUpdateBy(activitySaveParam.getUserUuid());
            marketingActivityMapper.editIncludeNull(marketingActivityDto);
        }
        return ResponseData.buildSuccessResponse("保存成功", Boolean.TRUE);
    }

    @Override
    public ResponseData<Boolean> setActive(AdminStatusParam statusParams) {
        List<MarketingActivityDto> list = marketingActivityMapper.list(MapUtils.build("uuid", statusParams.getUuid()));
        if (CollectionUtils.isNotEmpty(list)) {
            MarketingActivityDto activityDto = list.get(0);
            // 判断活动最大数量，超过则关闭最近一条
            if (!maxActivity(activityDto.getShowType(), activityDto.getBusinessType())) {
                marketingActivityMapper.shutdownLatelyOne(activityDto.getBusinessType(), activityDto.getShowType());
            }
            MarketingActivityDto marketingActivityDto = new MarketingActivityDto();
            marketingActivityDto.setUuid(statusParams.getUuid());
            marketingActivityDto.setStatus(statusParams.getStatus());
            marketingActivityDto.setPutInDateOn(new Date());
            marketingActivityDto.setUpdateOn(new Date());
            marketingActivityDto.setUpdateBy(statusParams.getUserUuid());
            int count = marketingActivityMapper.edit(marketingActivityDto);
            if (count > 0) {
                return ResponseData.buildSuccessResponse("设置状态成功", Boolean.TRUE);
            }
        }
        return ResponseData.buildSuccessResponse("设置状态失败", Boolean.FALSE);
    }

    @Override
    public ResponseData<List<MarketingActivityDto>> getActivities(Map<String, Object> map) {
        List<String> uuidList = new ArrayList<>();
        List<MarketingActivityDto> list = marketingActivityMapper.getActivities(map);
        //根据区域代码没查到 再查
        if (CollectionUtils.isEmpty(list)) {
            map.remove("adCode");
            map.put("cityUuid", "ALL");
            list = marketingActivityMapper.getActivities(map);
        }
        //根据城市没有查询到，用全国再查
        if (CollectionUtils.isEmpty(list)) {
            map.remove("adCode");
            map.put("cityUuid", "ALL");
            list = marketingActivityMapper.getActivities(map);
        }
        for (MarketingActivityDto marketingActivityDto : list) {
            uuidList.add(marketingActivityDto.getUuid());
        }
        //更新展示量
        if (uuidList.size() > 0) {
            marketingActivityMapper.updateShowCount(uuidList);
        }
        return ResponseData.buildSuccessResponse(list);
    }


    @Override
    public ResponseData<Boolean> updateSort(List<AdminActivitySortParam> list) {
        return ResponseData.buildSuccessResponse("排序成功", marketingActivityMapper.updateSort(list) > 0);
    }

    @Override
    public ResponseData<Boolean> updateCilckCount(String activityUuid) {
        int resultCode = marketingActivityMapper.updateClickCount(activityUuid);
        if (resultCode > 0) {
            return ResponseData.buildSuccessResponse("增加活动点击量成功", Boolean.TRUE);
        }
        return ResponseData.buildSuccessResponse("增加活动点击量失败", Boolean.FALSE);
    }


    @Override
    public ResponseData<List<MarketingActivityDto>> activityQuartz(String appid) {
        return ResponseData.buildSuccessResponse(marketingActivityMapper.activityQuartz(appid));
    }
}